const {exec, escape} = require('../db/mysql')

// 获取所有权限
const getAuthorityList = async () => {
  const sql = `select *
               from authority;`
  return await exec(sql)
}
// 新增一条权限，不是真的插入一条记录，而是修改列属性(修改多个)
const newAuthority = async (array) => {
  array.forEach(item => {
    item = escape(item)
  })
  let sql = `update authority
               set isown = 0 where `
  for (let i = 0; i < array.length; i++) {
    sql += ` id = ${array[i]}`
    if (i !== array.length - 1) {
      sql += ` or `
    }
  }
  return await exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}
// 删除一条权限，不是真的删除一条记录，而是修改列属性
const delAuthority = async (arr) => {
  arr.forEach(item => {
    item = escape(item)
  })
  let sql = `update authority set isown = 1 where `
  for (let i = 0; i < arr.length; i++) {
    sql += `id = ${arr[i]}`
    if (i !== arr.length - 1) {
      sql += ' or '
    }
  }
  return await exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}
// 获取权限详情
const getAuthorityDetail = async (name) => {
  name = escape(name)
  const sql = `select * from authority where name = ${name} and isown = 0;`
  return await exec(sql).then(rows => {
    return rows[0] || {}
  })
}

module.exports = {
  getAuthorityList,
  newAuthority,
  delAuthority,
  getAuthorityDetail
}
